import 'package:flutter/material.dart';

void main() {
  runApp(const DartFeaturesApp());
}

class DartFeaturesApp extends StatelessWidget {
  const DartFeaturesApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dart 语言特性演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const FeatureDemoScreen(),
    );
  }
}

class FeatureDemoScreen extends StatefulWidget {
  const FeatureDemoScreen({super.key});

  @override
  State<FeatureDemoScreen> createState() => _FeatureDemoScreenState();
}

class _FeatureDemoScreenState extends State<FeatureDemoScreen> {
  String _output = '';
  bool _isLoading = false;
  final ScrollController _scrollController = ScrollController();

  // 1. 内置类型演示
  void _runBuiltInTypesDemo() {
    _clearOutput();
    _log("\n=== 内置类型演示 ===");

    // 数值类型
    int integer = 42;
    double decimal = 3.14;
    num number = 100;

    _log("整数: $integer");
    _log("浮点数: $decimal");
    _log("数值运算: ${integer * decimal}");

    // 字符串类型
    String name = "Alice";
    String message = "Hello, ${name}!";
    String rawString = r"换行符示例 \n";

    _log("字符串: $message");
    _log("原始字符串: $rawString");

    // 布尔类型
    bool isReady = true;
    bool hasError = false;

    _log("布尔值: isReady = $isReady, hasError = $hasError");

    // 列表 (List)
    List<String> fruits = ["apple", "banana", "cherry"];
    fruits.add("date");
    _log("列表: ${fruits.join(", ")}");

    // 集合 (Set)
    Set<int> numbers = {1, 2, 2, 3};
    numbers.add(4);
    _log("集合: ${numbers.toList()}");

    // 映射 (Map)
    Map<String, int> scores = {"Bob": 90, "Alice": 85};
    scores["Charlie"] = 80;
    _log("映射: ${scores.entries.join(", ")}");
  }

  // 2. 记录类型演示
  void _runRecordsDemo() async {
    _clearOutput();
    _log("\n=== 记录类型演示 ===");

    // 创建记录
    var point = (x: 10, y: 20);
    _log("记录: ${point}");

    // 解构记录
    var (x: x, y: y) = point;
    _log("解构坐标: x = $x, y = $y");

    // 记录作为函数返回值
    (String, int) getUser() => ("John", 30);
    var (name, age) = getUser();
    _log("用户信息: $name, $age 岁");
  }

  // 3. 集合操作演示
  void _runCollectionsDemo() {
    _clearOutput();
    _log("\n=== 集合操作演示 ===");

    // 列表操作
    List<int> list = [1, 2, 3];
    list.removeAt(1);
    _log("列表移除元素后: ${list}");
    _log("列表是否为空: ${list.isEmpty}");

    // 集合运算
    Set<int> setA = {1, 2, 3};
    Set<int> setB = {3, 4, 5};
    _log("并集: ${setA.union(setB)}");
    _log("交集: ${setA.intersection(setB)}");

    // 映射遍历
    Map<String, String> planets = {"Mercury": "closest", "Venus": "hottest"};
    planets.forEach((key, value) => _log("$key: $value"));
  }

  // 4. 泛型演示
  void _runGenericsDemo() {
    _clearOutput();
    _log("\n=== 泛型演示 ===");

    // 泛型类使用
    var stringStack = Stack<String>();
    stringStack.push("A");
    stringStack.push("B");
    _log("弹出元素: ${stringStack.pop()}");

    // 泛型函数
    int identity<T>(T value) => value as int;
    _log("泛型函数结果: ${identity(42)}");

    // 类型参数约束
    var pair = Pair(10, 20);
    _log("是否有序: ${pair.isOrdered()}");
  }

  // 5. 类型定义演示
  void _runTypedefsDemo() {
    _clearOutput();
    _log("\n=== 类型定义演示 ===");

    // 函数类型别名
    CompareFunction compare = (a, b) => a - b;
    _log("比较结果: ${compare(5, 3)}");

    // 集合类型别名
    StringList names = ["Alice", "Bob"];
    names.add("Charlie");
    _log("类型定义列表: ${names}");
  }

  // 6. 类型系统演示
  void _runTypeSystemDemo() {
    _clearOutput();
    _log("\n=== 类型系统演示 ===");

    dynamic obj = "Hello";

    // 类型检查
    if (obj is String) {
      _log("是字符串类型");
    }

    // 类型转换
    String str = obj as String;
    _log("转换后字符串: ${str.length}");

    // 断言
    int? x = 5;
    assert(x != null, "x 不能为 null");
    _log("断言通过: x = $x");
  }

  // 运行所有演示
  void _runAllDemos() async {
    setState(() {
      _isLoading = true;
      _output = '正在运行所有演示...\n';
    });

    await Future.delayed(const Duration(milliseconds: 500));

    _runBuiltInTypesDemo();
    await Future.delayed(const Duration(milliseconds: 800));

    _runRecordsDemo();
    await Future.delayed(const Duration(milliseconds: 800));

    _runCollectionsDemo();
    await Future.delayed(const Duration(milliseconds: 800));

    _runGenericsDemo();
    await Future.delayed(const Duration(milliseconds: 800));

    _runTypedefsDemo();
    await Future.delayed(const Duration(milliseconds: 800));

    _runTypeSystemDemo();

    setState(() {
      _isLoading = false;
    });
  }

  // 辅助方法
  void _log(String message) {
    setState(() {
      _output += '$message\n';
      _scrollToBottom();
    });
  }

  void _clearOutput() {
    setState(() {
      _output = '';
    });
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dart 语言特性演示'), centerTitle: true),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 控制按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: [
                ElevatedButton(
                  onPressed: _runBuiltInTypesDemo,
                  child: const Text('内置类型'),
                ),
                ElevatedButton(
                  onPressed: _runRecordsDemo,
                  child: const Text('记录类型'),
                ),
                ElevatedButton(
                  onPressed: _runCollectionsDemo,
                  child: const Text('集合操作'),
                ),
                ElevatedButton(
                  onPressed: _runGenericsDemo,
                  child: const Text('泛型'),
                ),
                ElevatedButton(
                  onPressed: _runTypedefsDemo,
                  child: const Text('类型定义'),
                ),
                ElevatedButton(
                  onPressed: _runTypeSystemDemo,
                  child: const Text('类型系统'),
                ),
                ElevatedButton(
                  onPressed: _runAllDemos,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (_isLoading)
                        const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(
                            color: Colors.white,
                            strokeWidth: 2,
                          ),
                        ),
                      if (_isLoading) const SizedBox(width: 8),
                      const Text('运行全部'),
                    ],
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // 输出区域
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.grey.shade50,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      color: Colors.grey.shade200,
                      child: const Text(
                        '输出结果',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ),
                    Expanded(
                      child: SingleChildScrollView(
                        controller: _scrollController,
                        padding: const EdgeInsets.all(12),
                        child: SelectableText(
                          _output.isEmpty ? '点击上方按钮运行演示...' : _output,
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 14,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 泛型类定义
class Pair<T extends Comparable<T>> {
  final T first, second;
  Pair(this.first, this.second);
  bool isOrdered() => first.compareTo(second) < 0;
}

class Stack<T> {
  final List<T> _items = [];

  void push(T item) => _items.add(item);
  T pop() => _items.removeLast();
}

// 类型定义
typedef CompareFunction = int Function(int a, int b);
typedef StringList = List<String>;
